package com.example.sixtrainingdemo.adapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sixtrainingdemo.R;
import com.example.sixtrainingdemo.entity.Goods;
import com.example.sixtrainingdemo.entity.Photo;

import java.util.List;

public class SaleGoodsListAdapter extends RecyclerView.Adapter<SaleGoodsListAdapter.ViewHolder> {

   private List<Goods> mList;

   public SaleGoodsListAdapter(List<Goods> list){
      mList = list;
   }

   public void updateData(List<Goods> list) {
      mList.clear();
      mList = list;
      notifyDataSetChanged();
   }

   @NonNull
   @Override
   public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.goods_item_sale, null);
      ViewHolder viewHolder = new ViewHolder(view);
      return viewHolder;
   }


   public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
      Goods goods = mList.get(position);
      holder.textView1.setText(goods.getName());
      holder.textView2.setText("$ " + goods.getPrice() + "/" + goods.getUnit());

      List<Photo> photoList = goods.getPhotoList();
      if (photoList != null && photoList.size() > 0) {
         byte[] byteArray = photoList.get(0).getData();
         Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
         holder.photo.setImageBitmap(bitmap);
      } else {
         holder.photo.setImageResource(R.mipmap.ic_launcher);
      }

   }

   @Override
   public int getItemCount() {
      return mList.size();
   }

   public class ViewHolder extends RecyclerView.ViewHolder {
      ImageView photo;
      TextView textView1;
      TextView textView2;

      public ViewHolder(@NonNull View itemView) {
         super(itemView);
         photo = itemView.findViewById(R.id.goods_photo);
         textView1 = itemView.findViewById(R.id.goods_name);
         textView2 = itemView.findViewById(R.id.goods_price);
      }
   }
}
